from mg_app_framework import MesCode, get_organization
from tornado_request_mapping import request_mapping

from common_bind_service.common.base.base_handler import BaseHandler
from common_bind_service.common.utils.web_utils import WebFileStream
from common_bind_service.pkg.excel.excel_operate import ExcelOperate
from common_bind_service.service.container_mark_config_service import ContainerMarkConfigService


@request_mapping('/container_mark_config')
class ContainerMarkConfigHandler(BaseHandler):
    """维护容器码规则的接口"""

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.container_config_service = ContainerMarkConfigService()

    @request_mapping('/full_import', 'post', '全量导入码值配置规则')
    async def full_import(self):
        # 检查文件
        files = self.request.files
        file_obj_list = files.get('file')
        if not file_obj_list:
            return self.send_response_data(MesCode.fail, '', '上传excel文件为空')

        response = await self.container_config_service.full_import_data(file_obj_list[0])
        return self.send_response_data(response.code, response.data, response.msg)

    @request_mapping('/export', 'get', '配置规则导出')
    async def formula_export(self):
        response = await self.container_config_service.get_all()
        if response.code == MesCode.success:
            bio = ExcelOperate.get_excel_data(response.data['data_header'], response.data['data'])
            filename = f'{get_organization()}~容器码规则列表.xlsx'
            return self.send_response_file(filename, WebFileStream(bio))
        else:
            return self.send_response_data(response.code, response.data, response.msg)

